﻿// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using k8s;
using k8s.Exceptions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;

namespace Steeltoe.Common.Kubernetes
{
    public static class KubernetesClientHelpers
    {
        public static IKubernetes GetKubernetesClient(IConfiguration configuration, KubernetesApplicationOptions appInfo = null, Action<KubernetesClientConfiguration> kubernetesClientConfiguration = null, ILogger logger = null)
        {
            appInfo ??= new KubernetesApplicationOptions(configuration);

            KubernetesClientConfiguration k8sConfig = null;

            try
            {
                if (appInfo.Config.Paths.Any())
                {
                    var delimiter = Platform.IsWindows ? ';' : ':';
                    var joinedPaths = appInfo.Config.Paths.Aggregate((i, j) => i + delimiter + j);
                    Environment.SetEnvironmentVariable("KUBECONFIG", joinedPaths);
                }

                k8sConfig = KubernetesClientConfiguration.BuildDefaultConfig();
            }
            catch (KubeConfigException e)
            {
                // couldn't locate .kube\config or user-identified files. use an empty config object and fall back on user-defined Action to set the configuration
                logger?.LogWarning(e, "Failed to build KubernetesClientConfiguration using files at configured or default location, creating an empty config...");
            }

            kubernetesClientConfiguration?.Invoke(k8sConfig ?? new KubernetesClientConfiguration());

            return new k8s.Kubernetes(k8sConfig);
        }
    }
}
